import React, { Fragment } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import {
    Table, Card, Button, List,
    Popover, Divider, Avatar,
    Spin, Select, Icon, Input, Menu, Dropdown,
    message, TreeSelect, Form, Row, Popconfirm,
    Col, InputNumber, Modal, Tooltip,Checkbox
} from 'antd';
import CheckAllBox from '@/components/CheckAllBox/index';
import styles from './index.less';
const Option = Select.Option;
const InputGroup = Input.Group;
const Search = Input.Search;
const namespace = 'customertag'
const FormItem = Form.Item;


@Form.create()
class Tags extends React.Component {
    state = {
        selectedTagIds: [],
        tagType: 0,
        tagName: '',

        paginationProps: {
            showSizeChanger: true,
            showQuickJumper: false,
            showTotal: total => `共 ${total} 条记录`,
            pageSize: 10,
            total: 0,
            pageIndex: 1,
        },
        cardLoading:true,
        selectedRows:[],
        isChecked:false,
        indeterminate:false
    }
    constructor(props) {
        super(props);
    }
    componentWillMount() {
      window.Isoption = false;
        this.GetList();
    }
    componentDidMount() {
      window.Isoption = true;
    }

    GetList = () => {
        const { dispatch, form } = this.props;
        const {selectedTagIds}=this.state;
        let values = { tagType: this.state.tagType, tagName: this.state.tagName, pageIndex: this.state.paginationProps.pageIndex, pageSize: this.state.paginationProps.pageSize }
        if (values.tagType == 0) {
            delete values.tagType;
        }
        dispatch({
            type: `${namespace}/TagList`,
            param: values,
            callback: (data) => {
                this.setState({ paginationProps: { ...this.state.paginationProps, total: data.Total },cardLoading:false })
                if(selectedTagIds.length>0){
                  this.setState({
                    selectedTagIds: []
                  })
                }
              }

        });
    }
    setTagType = value => {

        this.setState({ tagType: value }, () => {
            this.GetList();
        })

    }
    search = value => {
        this.setState({ tagName: value }, () => {
            this.GetList();
        })
    }
    onChange = data => {
        let { dispatch } = this.props;
        let { paginationProps } = this.state;
        let pagination = {
            ...paginationProps,
            ...data, pageIndex: data.current
        };
        this.setState({ paginationProps: pagination }, () => {
            this.GetList();
            this.child.cancelChecked();
        })
    };
    deleteTag = (tagId) => {

        let { dispatch } = this.props;
        dispatch({
            type: `${namespace}/DelTag`,
            param: { Id: tagId },
            callback: (data) => {

                message.success('删除成功');
                this.GetList();
                this.child.cancelChecked();
            }

        });
    }

    deleteTags = () => {
        const { selectedTagIds } = this.state;
        if (selectedTagIds.length < 1) {
            return message.error('请选择标签');
        }
        let { dispatch } = this.props;
        dispatch({
            type: `${namespace}/BatchDelTag`,
            param: { ids: selectedTagIds },
            callback: (data) => {
                message.success('删除成功');
                this.GetList();
                this.child.cancelChecked();
            }

        });
    }
    ExportTag = () => {
        const { selectedTagIds } = this.state;
        if (selectedTagIds.length < 1) {
            return message.error('请选择标签');
        }
        const { oemInfo } = this.props;
        let { dispatch } = this.props;
        //var tempwindow = window.open('', '下载');//先打开临时窗体，由于是点击事件内触发，不会被拦截
        dispatch({
            type: `${namespace}/ExportTag`,
            param: { ids: selectedTagIds },
            callback: {
                success: (data) => {
                    message.success('请求成功，将打开新窗口......');
                    var link = document.createElement('a');
                    link.innerHTML="下载";
                    link.href = oemInfo.cdnUrl + '/' + data.Path;

                    link.download='会员标签.xls';
                    link.click();
                },
                error: (data) => {

                }
            }

        });
    }
    addTag = () => {
        router.replace({
            pathname: `/${window.storeId}/customer/tags/add`,
        });
    }
    editTag = (id) => {
        router.replace({
            pathname: `/${window.storeId}/customer/tags/edit/${id}`,
        });
    }
    onSelectChange = (selectedTagIds,selectedRows) => {
      this.child.onChange(selectedTagIds);
      this.setState({ selectedTagIds, selectedRows});
    };
    render() {
        const {
            form: { getFieldDecorator },
            customertag, loading
        } = this.props;
        const { selectedTagIds, cardLoading, selectedRows } = this.state;
        const rowSelection = {
            selectedRowKeys: selectedTagIds,
            onChange: this.onSelectChange,
            getCheckboxProps: record => ({
                disabled: record.IsSystem,
            }),
        };

        const columns = [{
            title: '标签名称',
            dataIndex: 'Name',
            key: 'Name',
            width: '15%',
            align: 'left',
        }, {
            title: '用户数量',
            dataIndex: 'MemberCount',
            key: 'MemberCount',
            width: '10%',
            align: 'right',
        }, {
            title: '创建时间',
            dataIndex: 'CreateTime',
            key: 'CreateTime',
            width: '20%',
            align: 'left',
        }, {
            title: '标签类型',
            key: 'TagType',
            dataIndex: 'TagType',
            width: '10%',
            align: 'left',
        }, {
            title: '标签条件',
            key: 'Info',
            width: '25%',
            align: 'left',
            render: (text, data) => {
                if(data.TagType==="系统标签"){
                  return (
                    < div >
                        {data.Info}
                    </div>
                  )
                }else{
                  if (data.Info.length > 15) {
                    return (
                        < div >
                            {data.Info.substring(0, 15)+'...'}
                            <Tooltip title={data.Info}>
                                <a>详情</a>
                            </Tooltip>
                        </div>
                    )
                  } else {
                      return (
                          < div >
                              {data.Info}
                          </div>
                      )
                  }
                }

            },
        }, {
            title: '操作',
            key: 'option',
            width: '15%',
            align: 'right',
            render: (text, data) => (
                data.IsSystem ? <div style={{ color: "#8c8c8c" }}>不可操作</div> :
                    < div >

                        <a onClick={() => this.editTag(data.Id)}>
                            编辑
                    </a>
                        <Divider type="vertical" />
                        <Popconfirm title="确认删除？" onConfirm={() => this.deleteTag(data.Id)} okText="确定" cancelText="取消"> <a>删除</a>  </Popconfirm>

                    </ div>

            ),
        }];

        const props={
          dataList:customertag.PageData.DataList,
          onSelectChange:this.onSelectChange,
          selectedRows:selectedRows,
          condition:'IsSystem'
        }
        return (
            <Fragment>
              <Spin spinning={cardLoading} >
                <Card bordered={false}>
                    <div style={{marginBottom:16}}>
                      <Button type="primary" onClick={this.addTag}>新增标签</Button>
                    </div>
                    <div className={styles.NavButtons}>
                    {/* <div className={styles.checkAll}>
                      <Checkbox checked={isChecked} indeterminate={indeterminate} onChange={this.selectAll}>当页全选</Checkbox>
                    </div> */}
                        <CheckAllBox {...props} onRef={(ref) => { this.child = ref }}/>
                        <Button onClick={this.ExportTag}>导出标签</Button>
                        <Popconfirm
                            icon={false}
                            title={'确认删除？'}
                            onConfirm={() => this.deleteTags()}
                            cancelText='取消'
                            okText='删除'
                        >
                            <Button>批量删除</Button>
                        </Popconfirm>

                        <InputGroup compact>
                            <Select defaultValue={0} onChange={this.setTagType} style={{ width: 126 }}>
                                <Option value={0}>所有标签</Option>
                                <Option value={1}>手动标签</Option>
                                <Option value={2}>自动标签</Option>
                            </Select>
                            <Search
                                placeholder="请输入标签名称"
                                onSearch={this.search}
                                style={{ width: 229 }}
                            />
                        </InputGroup>

                    </div>
                    <div className={styles.tagsTable}>
                      <Table
                          rowSelection={rowSelection}
                          columns={columns}
                          loading={loading}
                          rowKey={data => data.Id}
                          dataSource={customertag.PageData.DataList ? customertag.PageData.DataList : []}
                          onChange={this.onChange.bind(this)}
                          pagination={this.state.paginationProps}
                      />
                    </div>
                </Card>
                </Spin>
            </Fragment>
        )
    }
}
export default connect(({ customertag, global, loading }) => ({
    customertag,
    oemInfo: global.oemInfo,
    loading: loading.effects['customertag/TagList'],
}))(Tags);
